import sys
import webbrowser
import math
import random
import os
import tkinter as tk
from tkinter import messagebox
from tkinter import filedialog
import time
import requests


root = tk.Tk()
root.withdraw()

vars = {}
version = "25w12b"
def f4t(c):
    c = str(c).strip()
    if c in vars.keys():
        return vars[c]
    elif c.startswith("\""):
        return c[1:-1]
    elif "<" in c:
        return int(f4t(c.split("<")[0])) < int(f4t(c.split("<")[1]))
    elif ">" in c:
        return int(f4t(c.split(">")[0])) > int(f4t(c.split(">")[1]))
    elif "==" in c:
        return int(f4t(c.split("==")[0])) == int(f4t(c.split("==")[1]))
    elif "!=" in c:
        return int(f4t(c.split("!=")[0])) != int(f4t(c.split("!=")[1]))
    elif "**" in c:
        return int(f4t(c.split("**")[0])) ** int(f4t(c.split("**")[1]))
    elif "+" in c:
        return int(f4t(c.split("+")[0])) + int(f4t(c.split("+")[1]))
    elif "-" in c:
        return int(f4t(c.split("-")[0])) - int(f4t(c.split("-")[1]))
    elif "*" in c:
        return int(f4t(c.split("*")[0])) * int(f4t(c.split("*")[1]))
    elif "/" in c:
        return int(f4t(c.split("/")[0])) / int(f4t(c.split("/")[1]))
    elif "%" in c:
        return int(f4t(c.split("%")[0])) % int(f4t(c.split("%")[1]))
    else:
        return run(c)
def list2str(l):
    return str([f4t(i) for i in l]).replace('"', "").replace("'","").replace("[", "").replace("]", "").replace(",", "")

def run(c: str):
    c = c.strip().replace("\n", "")
    if c == "this()":
        print("""丑陋胜于美丽：代码应该是粗糙的，不仅仅是功能上的，还包括代码的外观和结构。
晦涩胜于明了：代码应该是难以理解的。使用模糊的命名和风格，使得代码无法自我解释。
复杂胜于简洁：复杂的实现优于简单的。尽量保持代码复杂，增加不必要的复杂性。
凌乱胜于复杂：如果无法避免复杂性，代码之间的关系应该是混乱的，接口应该保持复杂。
嵌套胜于扁平：增加过多的嵌套层次，尽量保持代码的嵌套结构。
紧凑胜于间隔：紧凑的空间间隔可以降低代码的可读性，试图在一行代码中解决所有问题。
可读性不重要：代码的可读性是不重要的，它不仅不影响代码的维护，也不影响团队协作。
即使纯粹性胜过实用性，也应违反这些规则：纯粹性是重要的，但应以牺牲代码的清晰性和可维护性为代价。
错误应该默默地过去：应该模糊地捕获异常，避免编写能够捕获具体错误的代码。
面对不确定性，尝试去猜测：在多种可能性面前，应该寻找一种模糊的解决方案，而不是靠明显的解决方案。
现在不做比做好：袖手旁观通常比采取行动要好，但在行动前不应该仔细考虑。
如果实现难以解释，那它可能是个好主意：代码的实现应该是模糊和复杂的，这样才能难以理解和维护。
命名空间是一个糟糕的理念：应该避免使用命名空间来组织代码，降低代码的模块性和可重用性。""")
        return
    # 定义变量
    if c.startswith("let "):
        c = c.split("let ")[1]
        # 有赋值
        if "=" in c:
            c = c.split("=")
            vars[c[0].strip()] = f4t(c[1])
            return
        # 没赋值
        else:
            for v in c.split(","):
                vars[v.strip()] = None
            return
    # 变量赋值
    for v in vars.keys():
        if c.startswith(v) and "+=" in c and "." not in c:
            c = c.split(v)[1].split("+=")[1].strip()
            vars[v] = int(vars[v])+int(f4t(c))
            return
        if c.startswith(v) and "-=" in c and "." not in c:
            c = c.split(v)[1].split("-=")[1].strip()
            vars[v] = int(vars[v])+int(f4t(c))
            return
        if c.startswith(v) and "=" in c and "." not in c:
            c = c.split(v)[1].split("=")[1].strip()
            vars[v] = f4t(c)
            return
    if c.startswith("tanc."):
        c = c.split("tanc.")[1]
        if c.startswith("wei("):
            c = c.split("wei(")[1].split(")")[-2].split(", ")
            messagebox.showinfo("信息", list2str(c))
            return
        if c.startswith("buhaola("):
            c = c.split("buhaola(")[1].split(")")[-2].split(", ")
            messagebox.showwarning("警告", list2str(c))
            return
        if c.startswith("chucuola("):
            c = c.split("chucuola(")[1].split(")")[-2].split(", ")
            messagebox.showerror("错误", list2str(c))
            return
    if c.startswith("kongzhitai."):
        c = c.split("kongzhitai.")[1]
        if c.startswith("xieru("):
            c = c.split("xieru(")[1][:-1].split(", ")
            (list2str(c))
            return
        if c.startswith("baocuo("):
            c = c.split("baocuo(")[1].split(")")
            raise Exception(f4t(c))
    if c.startswith("shuxue."):
        c = "math." + c.split("shuxue.")[1]
        return eval(c)
    if c.startswith("suiji."):
        c = "random." + c.split("suiji.")[1]
        return eval(c)
    if c.startswith("lianjie("):
        c = c.split("lianjie(")[1].split(")")[-2]
        webbrowser.open(f4t(c))
        return
    if c.startswith("pd("):
        c = c.split("pd(")[1][:-1]
        flag = f4t(c.split(")")[0])
        c = c.split("{")[-1]
        if flag:
            for i in c.split("；"):
                run(i)
        return
    if "shuru()" in c:
        return input("> ")
    if c.startswith("wenjian."):
        c = c.split("wenjian.")[1]
        if c.startswith("xuanze()"):
            return filedialog.askopenfilename()
        if c.startswith("duqu("):
            file = c.split("duqu(")[1].split(")")[-2]
            with open(f4t(file), "r", encoding="utf-8") as f:
                return f.read()
        if c.startswith("xieru("):
            args = c.split("xieru(")[1].split(")")[-2].split(", ")
            path = f4t(args[0])
            connect = f4t(args[1])
            with open(path, "w", encoding="utf-8") as f:
                f.write(connect)
    if c.startswith("yunxing("):
        start, end = c.split("yunxing(")[1].split(")")[-2].split(", ")
        runs(start, end)
    if c.startswith("xunhuan("):
        c = c.split("xunhuan(")[1][:-1]
        count = f4t(c.split(")")[0])
        c = c.split("{")[-1]
        for j in range(int(count)):
            for i in c.split("；"):
                run(i)
        return
    for pn in plist:
        if c.startswith(pn):
            c=f'ps["{pn}"]{c.split(pn)[-1]}'
            return eval(c)
    return c

def runs(start, end):
    try:
        for i in range(int(start)-1, int(end)):
            run(commands[i])
    except Exception:
        runs(start, end)

if "-help" in sys.argv:
    print("""命令：gs.exe [选项] [文件]
选项：
-help        : 显示帮助信息
-upd         : 检查更新
-v           : 显示版本信息
-egg         : 为什么不去自己试试呢: )
plugin...    : 插件管理（开发中）
文件：
你的.gs文件路径，如：
C:/Users/Administrator/Desktop/test.gs
./files/test.gs""")
    sys.exit(0)

if "plugin" in sys.argv:
    sys.exit(0)

if "-upd" in sys.argv:
    print("开始检查更新...")
    release, snapshot = requests.get("http://gavascript.top/download/latest").text.split(",")
    print(f"\033[1;32m[稳定最新]：{release}\n\033[1;35m[快照最新]：{snapshot}\033[0m")
    if "w" in version:
        print(f"\033[1;34m[当前]：\033[1;35m[快照]{version}\033[0m")
    else:
        print(f"\033[1;34m[当前]：\033[1;32m[稳定]{version}\033[0m")
    if version == release:
        print("\033[1;34m已是最新\033[1;32m[稳定]\033[1;34m版，无需更新\033[0m")
    elif version == snapshot:
        print("\033[1;34m已是最新\033[1;35m[快照]\033[1;34m版，无需更新\033[0m")
    elif "w" in version:
        url = f"http://gavascript.top/download/gs1/{snapshot}.exe"
        if input(f"\033[1;34m是否更新到\033[1;35m[快照]{snapshot}\033[1;34m？(y/n)\033[0m") == "y":
            webbrowser.open(url)
            print(f"\033[1;34m浏览器没有打开请手动下载：\033[0m{url}")
    else:
        url = f"http://gavascript.top/download/gs1/{release}.exe\033[0m"
        if input(f"\033[1;34m是否更新到\033[1;32m[稳定]{release}\033[1;34m？(y/n)\033[0m") == "y":
            webbrowser.open(url)
            print(f"\033[1;34m浏览器没有打开请手动下载：\033[0m{url}")
    sys.exit(0)

if "-v" in sys.argv:
    print("GavaScript 1.x " + version)
    sys.exit(0)
if "-egg" in sys.argv:
    print("""          _____                    _____                    _____                    _____                    _____                    _____                    _____                    _____                    _____                _____          
         /\    \                  /\    \                  /\    \                  /\    \                  /\    \                  /\    \                  /\    \                  /\    \                  /\    \              /\    \         
        /::\    \                /::\    \                /::\____\                /::\    \                /::\    \                /::\    \                /::\    \                /::\    \                /::\    \            /::\    \        
       /::::\    \              /::::\    \              /:::/    /               /::::\    \              /::::\    \              /::::\    \              /::::\    \               \:::\    \              /::::\    \           \:::\    \       
      /::::::\    \            /::::::\    \            /:::/    /               /::::::\    \            /::::::\    \            /::::::\    \            /::::::\    \               \:::\    \            /::::::\    \           \:::\    \      
     /:::/\:::\    \          /:::/\:::\    \          /:::/    /               /:::/\:::\    \          /:::/\:::\    \          /:::/\:::\    \          /:::/\:::\    \               \:::\    \          /:::/\:::\    \           \:::\    \     
    /:::/  \:::\    \        /:::/__\:::\    \        /:::/____/               /:::/__\:::\    \        /:::/__\:::\    \        /:::/  \:::\    \        /:::/__\:::\    \               \:::\    \        /:::/__\:::\    \           \:::\    \    
   /:::/    \:::\    \      /::::\   \:::\    \       |::|    |               /::::\   \:::\    \       \:::\   \:::\    \      /:::/    \:::\    \      /::::\   \:::\    \              /::::\    \      /::::\   \:::\    \          /::::\    \   
  /:::/    / \:::\    \    /::::::\   \:::\    \      |::|    |     _____    /::::::\   \:::\    \    ___\:::\   \:::\    \    /:::/    / \:::\    \    /::::::\   \:::\    \    ____    /::::::\    \    /::::::\   \:::\    \        /::::::\    \  
 /:::/    /   \:::\ ___\  /:::/\:::\   \:::\    \     |::|    |    /\    \  /:::/\:::\   \:::\    \  /\   \:::\   \:::\    \  /:::/    /   \:::\    \  /:::/\:::\   \:::\____\  /\   \  /:::/\:::\    \  /:::/\:::\   \:::\____\      /:::/\:::\    \ 
/:::/____/  ___\:::|    |/:::/  \:::\   \:::\____\    |::|    |   /::\____\/:::/  \:::\   \:::\____\/::\   \:::\   \:::\____\/:::/____/     \:::\____\/:::/  \:::\   \:::|    |/::\   \/:::/  \:::\____\/:::/  \:::\   \:::|    |    /:::/  \:::\____\\
\:::\    \ /\  /:::|____|\::/    \:::\  /:::/    /    |::|    |  /:::/    /\::/    \:::\  /:::/    /\:::\   \:::\   \::/    /\:::\    \      \::/    /\::/   |::::\  /:::|____|\:::\  /:::/    \::/    /\::/    \:::\  /:::|____|   /:::/    \::/    /
 \:::\    /::\ \::/    /  \/____/ \:::\/:::/    /     |::|    | /:::/    /  \/____/ \:::\/:::/    /  \:::\   \:::\   \/____/  \:::\    \      \/____/  \/____|:::::\/:::/    /  \:::\/:::/    / \/____/  \/_____/\:::\/:::/    /   /:::/    / \/____/ 
  \:::\   \:::\ \/____/            \::::::/    /      |::|____|/:::/    /            \::::::/    /    \:::\   \:::\    \       \:::\    \                    |:::::::::/    /    \::::::/    /                    \::::::/    /   /:::/    /          
   \:::\   \:::\____\               \::::/    /       |:::::::::::/    /              \::::/    /      \:::\   \:::\____\       \:::\    \                   |::|\::::/    /      \::::/____/                      \::::/    /   /:::/    /           
    \:::\  /:::/    /               /:::/    /        \::::::::::/____/               /:::/    /        \:::\  /:::/    /        \:::\    \                  |::| \::/____/        \:::\    \                       \::/____/    \::/    /            
     \:::\/:::/    /               /:::/    /          ~~~~~~~~~~                    /:::/    /          \:::\/:::/    /          \:::\    \                 |::|  ~|               \:::\    \                       ~~           \/____/             
      \::::::/    /               /:::/    /                                        /:::/    /            \::::::/    /            \:::\    \                |::|   |                \:::\    \                                                       
       \::::/    /               /:::/    /                                        /:::/    /              \::::/    /              \:::\____\               \::|   |                 \:::\____\                                                      
        \::/____/                \::/    /                                         \::/    /                \::/    /                \::/    /                \:|   |                  \::/    /                                                      
                                  \/____/                                           \/____/                  \/____/                  \/____/                  \|___|                   \/____/                                                       """)
    sys.exit(0)
try:
    ps = {}
    sys.path.append(os.path.join(os.getcwd(), "plugins"))
    plist = os.listdir("plugins")
    for p in plist:
        if p.startswith("[disabled]") != True:
            ps[p] = __import__(p)
except:
    ps = {}
    plist = []
if len(sys.argv) == 1:
    if "w" in version:
        print(f"\033[1;33m警告：你正在使用一个快照版本\033[1;35m[{version}]\033[0m\033[1;33m，可能会存在一些问题，请不要在正式环境使用此版本。\033[0m")
    print("GavaScript 1.x " + version)
    while True:
        try:
            c = input(">>> ")
            print(f4t(c))
        except EOFError:
            sys.exit(0)
        except Exception as e:
            print(f'\033[1;31m错误：{e}\033[0m')

file = sys.argv[-1]
try:
    with open(file, "r", encoding="utf-8") as f:
        codes = f.read()
        commands = codes.split("//")
except Exception as e:
    print(e)
    sys.exit(1)

# 注释处理
i = 0
for c in commands[1:]:
    commands[i] = c.split("\n")[-1]
    i+=1
commands = "".join(commands).split(";")
for c in commands:
    run(c)
def test():
    t = time.time()
    for i in range(1, 80001):
        run(f'wenjian.duqu("E:/files/{i}.gs")')
    print('8w文件读取', time.time()-t, 's')
    run('let test=0')
    t = time.time()
    for i in range(500000):
        run('test+=1')
        run('test-=1')
    print('100w次变量加减', time.time()-t, 's')
    t = time.time()
    for i in range(250000):
        run('pd(1+1==2){test+=1}')
        run('pd(1+2==4){test-=1}')
        run('pd(3+2==5){test-=1}')
        run('pd(1+5==3){test+=1}')
    print('100w次分支', time.time()-t, 's')